import json

import pandas
from flask import (Blueprint, request, session)

from flaskr import Utils

bp = Blueprint('upload',__name__, url_prefix='/upload')

@bp.route('', methods = ['GET', 'POST'])
def upload():
    if request.method == 'POST':

        file_ = request.files['file']
        md5 = request.form.get('md5')
        file_result = Utils.readFile(file_, md5)

        if md5:
            file_result = file_result.head(200)

        #读取失败
        if(type(file_result) == bool and file_result == False):
            return {
                'code':500,
                'msg':'不支持该类型文件'
            }

        if type(file_result) is pandas.DataFrame:
            filename = file_.filename

            filename = filename.split('.', 1)[0]
            sheetTable = {}
            sheetJson = {}
            dataName = filename
            sheets = [dataName]

            sheetTable[filename] = Utils.dataFrameToHtml(file_result)
            sheetJson[filename] = Utils.dataFrameToJson(file_result)

            data = {
                'sheetTable': sheetTable,
                'sheetJson': sheetJson,
                'dataName': dataName,
                'sheets': sheets,
                'md5': md5,
            }

            session['data'] = data

            return {
                'code': 200,
                'msg': "读取成功",
                'data': data
            }

        #读取成功 将文件转换成html
        html = Utils.dataFrameToHtml(file_result)
        json_ = Utils.dataFrameToJson(file_result)

        sheets = Utils.getSheets(file_result)
        sheets = sheets

        data =  {
                'sheetTable': html,
                'sheetJson': json_,
                'dataName': file_.filename,
                'sheets' : sheets
            }

        session['data'] = data

        return {
            'code': 200,
            'msg': "读取成功",
            'data': data
        }

    else:
        return "please send post requste"
